<template>
  <q-page class="q-pa-md wrapBox">
    <div v-loading="loading">
      <div class="nav">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <el-image src="/svgs/modelApplication.svg" style="width: 17px;margin-top: 2px" fit />
          </el-breadcrumb-item>
          <el-breadcrumb-item>模型服务</el-breadcrumb-item>
          <el-breadcrumb-item><span style=" color: #333;">模型部署</span></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="datasetBox" style="position: relative">
        <div class="contentBox_title">
          <span>模型部署</span>
        </div>
        <div class="contentBox">
          <div class="searchWrap" style="margin-top: 10px">
            <div>
              <el-input
                v-model.trim="searchName"
                placeholder="搜索模型服务名称"
                spellcheck="false"
              >
                <template #prepend>
                  <el-select v-model="typeValue" placeholder="服务状态" style="width: 150px;background-color: #fff">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      @click="filterDataset"
                    />
                  </el-select>
                </template>
                <template #append>
                  <el-button :icon="Search" @click="filterDataset" />
                </template>
              </el-input>
            </div>
            <div>
              <el-button
                type="primary"
                size="default"
                @click="toCreateModelDeploy"
              >部署模型</el-button>
            </div>
          </div>
          <el-table :data="labelAssignData.results" style="width: 100%;margin-top: 15px"
                    :header-cell-style="{ background: '#eee', color: '#333333' }" border>
            <el-table-column align="center" prop="title" label="名称" width="180">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="toDeployDetail(row.id)">{{ row.title }}</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="modelStatus" label="部署状态" width="140">
              <template #default="scope">
                <div style="display: flex;align-items: center;justify-content: center">
                  <div :style="divBackGroundColor(scope.row.status)" style="width: 8px;height: 8px;border-radius: 50%;margin-right: 5px"></div>
                  <div>{{scope.row.modelStatus}}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="call_count" label="调用" />
            <el-table-column align="center" prop="create_time" label="创建时间" />
            <el-table-column align="center" prop="description" label="描述" />
            <el-table-column align="center" prop="labels" label="操作">
              <template #default="scope">
                <el-button :disabled="scope.row.status === 'stopped'" link type="primary" size="small" @click="stopModelDeploy(scope.row)">停止</el-button>
                <!--<el-button :disabled="scope.row.status === 'stopped'" link type="primary" size="small">校验</el-button>-->
                <el-button link type="primary" size="small" @click="editModelDeploy(scope.row)">修改</el-button>
                <el-button link type="primary" size="small" @click="startModelDeployDialogShow(scope.row)">启动</el-button>
                <el-button link type="primary" size="small" @click="deleteModelHandle(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <el-dialog v-model="deleteModelDialog" :show-close="false" width="500px" :close-on-click-modal="false">
        <template #header="{}">
          <div style="display: flex;justify-content:space-between;margin-top: 10px">
            <div style="display:flex;">
              <el-icon style="font-size: 20px; color: #FFA940"><WarningFilled /></el-icon>
              <span style="margin-left: 10px;color: #1D1D1D;font-weight: bold">删除提醒</span>
            </div>
          </div>
        </template>
        <div style="margin: 10px 0 0px 50px;padding: 0">
          <p>确定删除该服务吗?</p>
          <p>删除后不可恢复,请谨慎操作！</p>
        </div>
        <div style="display: flex;justify-content: flex-end;padding-bottom: 10px">
          <el-button type="primary" @click="deleteModelDialog = false">放弃删除</el-button>
          <el-button @click="emitDeleteCreateModel">继续删除</el-button>
        </div>
      </el-dialog>
      <el-dialog v-model="dialogSetData" title="修改服务" width="500" :show-close="false" @close="resetForm(setDataRef)" :close-on-click-modal="false">
        <box-loading v-if="loading" @click.stop></box-loading>
        <el-form ref="setDataRef" :model="setDataForm" :rules="setDataRules" label-position="right" label-width="130px"
                 style="max-width: 460px">
          <el-form-item label="服务名称：" prop="title">
            <el-input v-model.trim="setDataForm.title" style="width:300px" placeholder="请输入服务名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetForm(setDataRef)">取消</el-button>
            <el-button type="primary" @click="submitConfirm(setDataRef)">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="dialogStartModelDeploy" title="启动服务" width="500" :show-close="false" @close="resetForm(startModel)" :close-on-click-modal="false">
        <box-loading v-if="loading" @click.stop></box-loading>
        <el-form ref="startModel" :model="startModelDeployForm" :rules="startModelDeployRules" label-position="right" label-width="130px"
                 style="max-width: 460px">
          <el-form-item label="集群队列" prop="queue">
            <el-select v-model="startModelDeployForm.queue" class="m-2" placeholder="请选择仓库模型" style="width: 200px;margin-right: 10px;">
              <el-option v-for="item in modelQueuesList" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="部署资源" prop="source">
            <el-row>
              <el-col span="20" style="display: flex;margin-right: 25px">
                <span style="color: #1D1D1D;">CPU核数</span>
                <el-input v-model.trim.number="startModelDeployForm.source.cpu" placeholder="请输入" style="width: 100px;margin: 0 10px"></el-input>核
              </el-col>
              <el-col span="20" style="display: flex;margin-right: 25px">
                <span style="color: #1D1D1D;">内存</span>
                <el-input v-model.trim.number="startModelDeployForm.source.gpu" placeholder="请输入" style="width: 100px;margin: 0 10px"></el-input>M
              </el-col>
              <el-col span="20" style="display: flex">
                <span style="margin-right: 5px;color: #1D1D1D;">CPU卡数</span>
                <el-input v-model.trim.number="startModelDeployForm.source.memory" placeholder="请输入" style="width: 100px;margin: 0 10px"></el-input>卡
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="自动停止" prop="delivery">
            <div>
              <el-row>
                <el-col span="20" style="margin-right: 10px"><el-switch v-model="startModelDeployForm.is_auto_stop" /></el-col>
                <el-col span="20" v-if="startModelDeployForm.is_auto_stop">
                  <span style="margin-right: 5px;color: #1D1D1D;">时长</span>
                  <el-input v-model.trim.number="startModelDeployForm.stop_in_seconds" placeholder="请输入" style="width: 100px;margin: 0 10px" oninput="value=value.replace(/[^\d]/g,'')">></el-input>小时
                </el-col>
              </el-row>
              <el-row v-if="startModelDeployForm.is_auto_stop">
                <p>作业训练达到最大时间会被强制停止,若训练未完成可能造成作业失效</p>
              </el-row>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="startModelResetForm(startModel)">取消</el-button>
            <el-button type="primary" @click="startModelFrom(startModel)">
              启动
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!--停止启动-->
      <el-dialog v-model="stopModelDeployDialog" :show-close="false" width="500px" :close-on-click-modal="false">
        <template #header="{}">
          <div style="display: flex;justify-content:space-between;margin-top: 10px">
            <div style="display:flex;">
              <el-icon style="font-size: 20px; color: #FFA940"><WarningFilled /></el-icon>
              <span style="margin-left: 10px;color: #FFA940;font-weight: bold">删除提醒</span>
            </div>
          </div>
        </template>
        <div style="margin: 0 0 50px 50px;padding: 0">确定停止该服务吗?请谨慎操作！</div>
        <div style="display: flex;justify-content: flex-end;margin-right: 10px;margin-bottom: 10px">
          <el-button type="primary" @click="stopModelDeployDialog = false">放弃停止</el-button>
          <el-button @click="sureStopModelDeploy">确认停止</el-button>
        </div>
      </el-dialog>
    </div>
  </q-page>
</template>


<script setup lang="ts">
import { reactive, ref, computed, toRaw,onMounted} from "vue";
import { useRouter } from 'vue-router';
import {modelStore} from "stores/model";
import { Search } from '@element-plus/icons-vue'
import {
  getModelDeploymentsList,
  deleteModelDeploy,
  editorModelDeployHandle,
  getModelQueues,
  startModelDeployHandle,
  sureStopModelDeployHandle
} from "src/api/model";
import {ElMessage, ElMessageBox, ElNotification, FormInstance, FormRules} from "element-plus";
import {addFeatureset, featureSplitData, setFeatureset, validateFeaturesetName} from "src/api/dataset";
import { dataSetStore } from 'src/stores/dataSet';
const store=dataSetStore()
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id
const loading = ref(false)
const searchName = ref('')
const typeValue = ref('')
const userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;//判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username')//获取用户登录的用户名
const deleteModelDialog = ref(false);//模型部署删除弹框
let deleteModelData = ref({});
let editorModelDeploy = ref({});
let startModelDeployData = ref({});
let stopModelDeployData = ref({});

const dialogSetData = ref(false)
const setDataRef = ref<FormInstance>()
const startModel = ref<FormInstance>()

// 停止服务
const stopModelDeployDialog = ref(false);

const setDataForm = reactive({
  title: ''
})
onMounted(() => {
  // 通过store.quickStart.quickFlow判断是否显示快速入门提示
  if (store.quickStart.quickFlow) {
    store.setQuickStart({
      tipsPopup: true,
      quickFlow: true,
      flowNumber: store.quickStart.flowNumber,
      detailFlow:2
    })
  }
})

getQueues();//获取模型部署队列
//获取模型队列
function getQueues(){
  getModelQueues().then( (res:any) => {
    modelQueuesList.value = res.data;
  })
}
const dialogStartModelDeploy = ref(false);//启动服务
const modelQueuesList = ref([]);//集群队列
interface useInfoModel {
  queue:string;
  source: any,
  is_auto_stop: boolean,
  stop_in_seconds: string
}
const startModelDeployForm = reactive<useInfoModel>({
  queue: '',
  source: {
    cpu: '',
    memory: '',
    gpu: ''
  },
  is_auto_stop: false,
  stop_in_seconds: ''
})
let newRule = (rule:any, value:any, callback:any) => {
  if (value.cpu === '') {
    callback(new Error('请输入CPU核数'))
  } else if (value.memory === '') {
    callback(new Error('请输入内存数'))
  } else if (value.gpu === '') {
    callback(new Error(`请输入CPU卡数`))
  } else {
    callback()
  }
}
const startModelDeployRules = reactive<FormRules>({
  queue: [
    { required: true, message: '请选择集群队列', trigger: 'blur' }
  ],
  source: [
    { required: true, validator: newRule }
  ]
})
function startModelDeployDialogShow(row:any){
  dialogStartModelDeploy.value = true;
  startModelDeployData.value = row;
}
const startModelFrom = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const { queue,source,is_auto_stop,stop_in_seconds } = startModelDeployForm
      const params = {
        queue,
        cpu: source.cpu,
        gpu: source.gpu,
        memory: source.memory,
        is_auto_stop: is_auto_stop,
        stop_in_seconds: stop_in_seconds?stop_in_seconds:0
      }
      startModelDeployHandle(projectId,startModelDeployData.value.id,params).then( (res:any) =>{
        if( res.status === 200 ){
          ElMessage.success("启动模型部署成功！！！")
          dialogStartModelDeploy.value = false;
          getModelList();
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
function startModelResetForm(){
  dialogStartModelDeploy.value = false;
}
//确认停止模型部署
function stopModelDeploy(row:any){
  stopModelDeployDialog.value = true;
  stopModelDeployData.value = row;
}
function sureStopModelDeploy(){
  sureStopModelDeployHandle(projectId,stopModelDeployData.value.id).then( (res:any) =>{
    ElMessage.success("停止模型部署成功！！！")
    stopModelDeployDialog.value = false;
    getModelList();
  })
}

const validateTitle1 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('服务名称不能为空'));
    return;
  }else {
    callback();
  }
}
const setDataRules = reactive<FormRules>({
  title: [
    { required: true, validator: validateTitle1, trigger: 'blur', }
  ]
});

const options = [
  {
    value: 'all',
    label: '全部',
  },
  {
    value: 'start',
    label: '准备启动中',
  },
  {
    value: 'service',
    label: '服务中',
  },
  {
    value: 'stop',
    label: '停止',
  }
]
const tableData = [
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-02',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
]
const labelAssignData = ref(
  {
    "count": 0,
    "next": "string",
    "previous": "string",
    "results": [
      {
        "id": 0,
        "title": "string",
        "type": "git",
        "git_vendor": "gitlab",
        "git_version": "string",
        "git_uri": "string",
        "create_at": "2023-05-22T08:26:00.336Z",
        "description": "string"
      },
      {
        "id": 2,
        "title": "string22",
        "type": "git22",
        "git_vendor": "gitlab22",
        "git_version": "string22",
        "git_uri": "string22",
        "create_at": "222 2023-05-22T08:26:00.336Z",
        "description": "string22"
      },
      {
        "id": 3,
        "title": "string33",
        "type": "git33",
        "git_vendor": "gitlab33",
        "git_version": "string33",
        "git_uri": "string333",
        "create_at": "33 2023-05-22T08:26:00.336Z",
        "description": "333string"
      }
    ]
  }
)
// const filterTableData = computed(() =>
//   labelAssignData.results.filter(
//     (data) =>
//       !searchName.value ||
//       data.title.toLowerCase().includes(searchName.value.toLowerCase())
//   )
// );

const divBackGroundColor = (value:any) => {
  if (value === 'stopped') {
    return { backgroundColor: '#CDE7FF' } // 返回红色的十六进制颜色值
  } else if (value === 'blue') {
    return '0000FF'; // 返回蓝色的十六进制颜色值
  } else if (value === 'green') {
    return '00FF00'; // 返回绿色的十六进制颜色值
  } else {
    return '000000'; // 默认颜色，例如黑色的十六进制颜色值
  }
};
//跳转模型部署界面
function toCreateModelDeploy() {
  router.push({ name: 'model-deploy-create', params: { project_id: projectId } })
};
//跳转模型部署详情
function toDeployDetail(id:number){
  modelStore().dataset(id);
  router.push({name: 'model-deploy-detail'})
}
function editModelDeploy(row:any){
  dialogSetData.value = true;
  editorModelDeploy.value = row;
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  if (dialogSetData.value) dialogSetData.value = false
}
const submitConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      editorModelDeployHandle(projectId,editorModelDeploy.value.id,{ title: setDataForm.title }).then( (res:any) =>{
        ElMessage.success("修改成功！！！")
        dialogSetData.value = false;
        getModelList();
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}



getModelList();//获取模型部署列表
function getModelList() {
  loading.value = true
  getModelDeploymentsList(projectId).then((res: any) => {
    res.data.results.forEach( (item:any) => {
      item.modelStatus = dockerStatusChage(item.status);
    });
    labelAssignData.value = res.data;
  }).finally(() => {
    loading.value = false
  })
}

// 删除模型部署
function deleteModelHandle(row:any){
  deleteModelDialog.value = true
  deleteModelData.value = row;
};

function emitDeleteCreateModel(){
  const id = toRaw(deleteModelData.value.id)
  deleteModelDeploy(projectId,id).then( (res:any) =>{
    ElMessage.success("删除成功！！！")
    deleteModelDialog.value = false;
    getModelList();
  })
}
function dockerStatusChage(dockerStatus:any){
  switch (dockerStatus) {
    case 'stopped':
      return '停止';
    case 'running':
      return '服务中';
    case 'preparing':
      return '准备启动中';
  }
}
const toDataSetDetail = () => {
  router.push({ name:'model-deploy-detail' })
}
</script>

<style scoped lang="scss">
.wrapBox {
  padding: 0 !important;
  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: var(--nav-bg-color);
    height: 46px;
    ::v-deep .el-breadcrumb{
      display: flex;
      align-items: center;
    }
  }
  .datasetBox {
    margin: 0 20px;
    .contentBox_title{
      position: relative;
      display: flex;
      align-items: center;
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
      .icon{
        position: absolute;
        left: 90px;
        top: 22px;
        width: 17px;
      }
      .text{
        position: absolute;
        left: 104px;
        top: 19px;
        font-size: 12px;
        color: #3d5ce4;
        font-weight: 400;
        cursor: pointer;
      }
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
      .searchWrap{
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
//输入框placeholder样式
::v-deep .el-input__inner {
  &::placeholder {
    color: #ccc;
    font-size: 14px;
  }
  &::-webkit-input-placeholder {
    /* WebKit browsers 适配谷歌 */
    color: #ccc;
    font-size: 14px;
  }
  &:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 适配火狐 */
    color: #ccc;
    font-size: 14px;
  }
  &::-moz-placeholder {
    /* Mozilla Firefox 19+ 适配火狐 */
    color: #ccc;
    font-size: 14px;
  }
  &:-ms-input-placeholder {
    /* Internet Explorer 10+  适配ie*/
    color: #ccc;
    font-size: 14px;
  }
}
//点击下拉框，去掉输入框蓝色高亮显示
:deep(.el-input){
  --el-input-focus-border:#fff;
  --el-input-transparent-border: 0 0 0 0px;
  --el-input-border-color:var(--el-border-color);
  --el-input-hover-border:0px !important;
  --el-input-hover-border-color:var(--el-border-color);
  --el-input-focus-border-color:var(--el-border-color);
  --el-input-clear-hover-color:var(--el-border-color);
}
</style>
